define(function (require, exports, module) {

    // 通过 require 引入依赖
    // var $ = require('jquery');
    require('common');
    require('sui');
    var template = require('template');
    dateFormat(template);
    var rows = 20;
    var groupId;

    function initData() {
        getChannelData(1, rows, null, null);
        getUserData(1, rows, null, null);
    }

    $('#form-group').validate({
        rules: {
            groupName: {
                required: true,
                minlength: 2,
                maxlength: 20
            }
        },
        messages: {
            groupName: "请填写"
        },
        success: function () {
            createGroup();
            return false;
        }
    });

    $(document).on('click', '.check-add-user', function () {
        if ($(this).is(":checked")) {
            $('input[name="user-id"]').prop("checked", true);//全选
            $('.rowover-table tbody tr').addClass('tr-click');
        } else {
            $('input[name="user-id"]').prop("checked", false);//取消全选
            $('.rowover-table tbody tr').removeClass('tr-click')
        }
    }).on('click', '.check-add-channel', function () {
        if ($(this).is(":checked")) {
            $('input[name="channel-id"]').prop("checked", true);//全选
        } else {
            $('input[name="channel-id"]').prop("checked", false);//取消全选
        }
    }).on('click', '.query-channel', function () {
        var groupId = $('.create-group').attr('data-id');
        getChannelData(1, rows, 0, groupId);
    }).on('click', '.add-channel', function () {
        var inputs = $('input[name="channel-id"]');
        var ids = new Array();
        $.each(inputs, function (i, item) {
            if ($(item).is(':checked')) {
                // ids[i] = parseInt($(item).val());
                ids.push(parseInt($(item).val()));
            }
        });
        if (ids.length == 0) {
            toastInfo('请选择要添加的渠道');
            return;
        }
        var groupId = $('.create-group').attr('data-id');
        $.post('/group/addChannel', {ids: JSON.stringify(ids), groupId: groupId}, function (data) {
            switch (data.code) {
                case 0:
                    toastSuccess('添加成功');
                    getChannelData(1, rows, 0, groupId);
                    break;
                default :
                    toastError('添加失败');
            }
        });
    }).on('click', '.query-user', function () {
        var groupId = $('.create-group').attr('data-id');
        getUserData(1, rows, 0, groupId);
    }).on('click', '.add-user', function () {
        var inputs = $('input[name="group-user-id"]');
        var ids = new Array();
        $.each(inputs, function (i, item) {
            if ($(item).is(':checked')) {
                // ids[i] = parseInt($(item).val());
                ids.push(parseInt($(item).val()));
            }
        });
        if (ids.length == 0) {
            toastInfo('请选择要添加的账号');
            return;
        }
        var groupId = $('.create-group').attr('data-id');
        $.post('/group/addUser', {ids: JSON.stringify(ids), groupId: groupId}, function (data) {
            switch (data.code) {
                case 0:
                    toastSuccess('添加成功');
                    getUserData(1, rows, 0, groupId);
                    break;
                default :
                    toastError('添加失败');
            }
        });
    });

    function createGroup() {
        var groupName = $.trim($('#groupName').val());
        var groupLevel = $('#groupLevel').val();
        var groupType = $('#groupType').val();
        var groupRemark = $.trim($('#groupRemark').val());
        var data = {groupName: groupName, groupLevel: groupLevel, groupType: groupType, groupRemark: groupRemark};
        $('.create-group').prop('disabled', 'disabled');
        $.post('/group/add', data, function (o) {
            switch (o.code) {
                case 0:
                    var id = o.data;
                    $('.create-group').attr('data-id', id);
                    if (groupType == '1') {
                        $('.add-user').removeAttr('disabled');
                    } else if (groupType == '2') {
                        $('.add-channel').removeAttr('disabled');
                    }
                    groupId = id;
                    toastSuccess('新增群组成功');
                    getChannelData(1, rows, 0, groupId);
                    getUserData(1, rows, 0, groupId);
                    break;
                default:
                    toastError(o.msg);
                    $('.create-group').removeAttr('disabled');
            }
        })

    }

    function getChannelData(page, rows, groupChannelFlag, groupId) {
        var channelId = $.trim($('#channelId').val());
        var channelName = $.trim($('#channelName').val());
        var data = {
            channelId: channelId,
            channelName: channelName,
            page: page,
            rows: rows,
            channelStatus: '0',
            groupChannelFlag: groupChannelFlag,
            groupId: groupId
        };
        $.post('/group/listChannel', data, function (data) {
            switch (data.code) {
                case 0:
                    var list = data.data.list;
                    var count = data.data.count;
                    var html = template('tp-channel', {list: list});
                    $('#tab-channel tbody').empty();
                    $('#tab-channel tbody').html(html);
                    $('.channel-pagination').pagination('updateItemsCount', count);
                    break;
                default:
                    toastError('查询群组数据失败');
            }
        });
    }

    function getUserData(page, rows, groupUserFlag, groupId) {
        var accountName = $.trim($('#accountName').val());
        var data = {
            accountName: accountName,
            page: page,
            rows: rows,
            groupUserFlag: groupUserFlag,
            groupId: groupId
        };
        $.post('/group/listUser', data, function (data) {
            switch (data.code) {
                case 0:
                    var list = data.data.list;
                    var count = data.data.count;
                    var html = template('tp-user', {list: list});
                    $('#tab-user tbody').empty();
                    $('#tab-user tbody').html(html);
                    $('.user-pagination').pagination('updateItemsCount', count);
                    break;
                default:
                    toastError('查询数据失败');
            }
        });
    }

    $('.user-pagination').pagination({
        itemsCount: 0,
        pageSize: rows,
        showCtrl: true,
        displayPage: 6,
        onSelect: function (num) {
            getUserData(num, rows, 0, groupId)
        }
    });

    $('.channel-pagination').pagination({
        itemsCount: 0,
        pageSize: rows,
        showCtrl: true,
        displayPage: 6,
        onSelect: function (num) {
            getChannelData(num, rows, 0, groupId)
        }
    })

    function dateFormat(template) {
        template.helper('dateFormat', function (date, format) {
            date = new Date(date);
            var map = {
                "M": date.getMonth() + 1, //月份
                "d": date.getDate(), //日
                "h": date.getHours(), //小时
                "m": date.getMinutes(), //分
                "s": date.getSeconds(), //秒
                "q": Math.floor((date.getMonth() + 3) / 3), //季度
                "S": date.getMilliseconds() //毫秒
            };
            format = format.replace(/([yMdhmsqS])+/g, function (all, t) {
                var v = map[t];
                if (v !== undefined) {
                    if (all.length > 1) {
                        v = '0' + v;
                        v = v.substr(v.length - 2);
                    }
                    return v;
                }
                else if (t === 'y') {
                    return (date.getFullYear() + '').substr(4 - all.length);
                }
                return all;
            });
            return format;
        });
    }

    initData();
});